package com.jaryle.wenxin.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 描述:
 * 使用httpclient工具处理Http发起的post和get请求
 *
 * @author jaryle
 * @version V1.0
 * @create 2018-12-24
 */
public class HttpClientUtil {
    /**
     * 编写Get请求的方法。但没有参数传递的时候，可以使用Get请求
     *
     * @param url 需要请求的URL
     * @return 将请求URL后返回的数据
     */
    public static String HttpGet(String url)  {
//        HttpClient httpClient = new DefaultHttpClient();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // get method
        HttpGet httpGet = new HttpGet(url);

        //response
        HttpResponse response = null;
        try{
            response = httpClient.execute(httpGet);
        }catch (Exception e) {
            e.printStackTrace();
        }

        //get response into String
        String temp="";
        try{
            HttpEntity entity = response.getEntity();
            temp=EntityUtils.toString(entity,"UTF-8");
        }catch (Exception e) {
            e.printStackTrace();
        }
        return temp;

    }

    /**
     * 编写Post请求的方法。但有参数传递的时候，可以使用Post请求
     *
     * @param url 需要请求的URL
     * @param params post请求传递的参数
     * @return 将请求URL后返回的数据
     */
    public static String HttpPost(String url,String params) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
//        HttpClient httpClient = new DefaultHttpClient();
        // get method
        HttpPost httpPost = new HttpPost(url);

        // set header
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
        //set params
        try {
            httpPost.setEntity(new StringEntity(params,"UTF-8"));
        }catch (Exception e){
            e.printStackTrace();
        }
        //response
        HttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //get response into String
        String temp = "";
        try {
            HttpEntity entity = response.getEntity();
            temp = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
        }

        return temp;
    }
}
